const dao = require('../dao').node()
const { createPreRelation, createBackRelation } = require('../dao').relation()
const getNeo4jFromMongoDB = require('../dao').graph().getNeo4jFromMongoDB
const getRes = require('../util').getRes

// 获取节点列表
const getList = async (username, page, records, keywords, type) => {
  // 获取知识图谱连接器
  const neo = await getNeo4jFromMongoDB(username)
  // 获取节点
  const res = await dao.getNodeListByPage(neo, page, records, keywords, type)
  return getRes('success', res, '请求成功')
}

// 根据节点id，获取节点的信息以及一层关系网络
const getNodeInfo = async (username, nodeId) => {
  const neo = await getNeo4jFromMongoDB(username)
  const res = await dao.getNodeInfoById(neo, nodeId)
  return getRes('success', res, '请求成功')
}

// 根据节点id，修改节点的信息
const updateNodeInfo = async (username, nodeId, nodeName, nodeType, oldNodeType) => {
  const neo = await getNeo4jFromMongoDB(username)
  const res = await dao.updateNodeInfoById(neo, nodeId, nodeName, nodeType, oldNodeType)
  return getRes('success', res, '修改成功')
}

// 新增节点
const addNode = async (username, nodeName, nodeType, preNodeList, backNodeList) => {
  const neo = await getNeo4jFromMongoDB(username)
  // 创建节点本身
  const nodeId = await dao.createNode(neo, nodeName, nodeType)
  const promiseList = []
  // 处理前驱节点与节点的关系
  if (preNodeList.length !== 0) {
    promiseList.push(createPreRelation(neo, nodeId, preNodeList))
  }
  // 处理节点与后继节点的关系
  console.log(backNodeList)
  if (backNodeList.length !== 0) {
    promiseList.push(createBackRelation(neo, nodeId, backNodeList))
  }
  await Promise.all(promiseList)
  return getRes('success', {}, '添加成功')
}

// 删除节点列表
const deleteNodeList = async (username, ids) => {
  const neo = await getNeo4jFromMongoDB(username)
  // 删除节点
  const res = await dao.deleteNodeList(neo, ids)
  return getRes('success', res, '删除成功')
}

module.exports = {
  getList,
  getNodeInfo,
  updateNodeInfo,
  addNode,
  deleteNodeList
}